import {defineStore} from "pinia";
import {computed, ref} from "vue";

export const testStore = defineStore('test', {
    // 选项式API
    // state
    state() {
        return {
            count: 0,
            month: [1, 2, 4, 65, 546, 78, 9, 6]
        }
    },
    // actions 提供修改 state 数据的方法，与Vuex 不同，不是通过内置参数context 或 state 操作数据，【而是使用this 指向state】
    actions: {
        updateCount() {
            this.count++
        }
    },
    // 基于state 数据的计算结果，类似计算属性
    getters: {
        evenMonth() {
            return this.month.filter(e => e & 1 === 0)
        },
        oddMonth() {
            return this.month.filter(e => e & 1 === 1)
        }
    }
})

export const compositionTestStore = defineStore('compositionStore', () => {

    // state
    const count = ref(0)
    const month = ref([1, 2, 4, 65, 546, 78, 9, 6])

    // getters
    const evenMonth = computed(() => {
        const res = month.value.filter(e => e & 1 === 1)
        console.log(res)
        return month.value.filter(e => !(e & 1))
    })
    const oddMonth = computed(() => {
        return month.value.filter(e => e & 1)
    })

//    actions
    const increaseCount = () => {
        count.value++
    }
    const decreaseCount = () => {
        count.value--
    }
    const asyncIncreaseCount = () => {
        setTimeout(() => count.value += 2, 1000)
    }
    // 初始化count
    const initCount = (v) => {
        count.value = v
    }

    return {
        count,
        month,
        evenMonth,
        oddMonth,
        increaseCount,
        decreaseCount,
        asyncIncreaseCount,
        initCount
    }
}, {
    persist: true
})
